﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;

namespace DACK_MHTTUD_0912008_0912493
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            tbMatKhauMH.Text = "12345678";
            tbGiaTriIVMH.Text = "12345678";
            tbMatKhauGM.Text = "12345678";
            tbGiaTriIVGM.Text = "12345678";
        }
        public static string publicAndPrivateKeys = "";
        public static string justPublicKey = "";

        string Path_PrivateKey = "private_key";
        string Path_PublicKey = "public_key";
        string Path_KeyPairs = "Key_Pairs";
        string Path_DigitalSignature = "Diagital_Signature_RSA";

        private void btGenerateKeypairs_Click(object sender, EventArgs e)
        {
            CspParameters cspParameters = new CspParameters();
            cspParameters.Flags = CspProviderFlags.UseMachineKeyStore;
            cspParameters.KeyContainerName = Guid.NewGuid().ToString();
            int bitStrength = int.Parse(nudBitStrength.Value.ToString());
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(bitStrength, cspParameters))
            {
                publicAndPrivateKeys = RSA.ToXmlString(true);
                //justPublicKey = RSA.ToXmlString(false);

                clsXML.SaveStringXMLToFile(publicAndPrivateKeys, Path_KeyPairs, saveFileDialog, "Save KeyPairs in RSA");
                //clsXML.SaveStringXMLToFile(justPublicKey, Path_PublicKey, saveFileDialog1, "Save Public Key in RSA");
            }
        }

        private void btBrownsSignMessage_Click(object sender, EventArgs e)
        {
            openFileDialog.Title = "Open file to sign";
            openFileDialog.Filter = "All files (*.*)|*.*";
            openFileDialog.FileName = "";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                tbPathSignMessage.Text = openFileDialog.InitialDirectory + openFileDialog.FileName;
            }
        }

        private void btBrownsSignKeypairs_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = "KeyPairs in RSA (*.rsakey)|*.rsakey";
            openFileDialog.Title = "Open KeyPairs in RSA";
            openFileDialog.FileName = "";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                tbPathSignKeypairs.Text = openFileDialog.InitialDirectory + openFileDialog.FileName;
            }
        }

        private void btSignInMessage_Click(object sender, EventArgs e)
        {
            string strCheckInput = clsChecker.CheckInPutSignAvailable(tbPathSignMessage, tbPathSignKeypairs);
            if (string.IsNullOrEmpty(strCheckInput))
            {
                // hash file 
                Type_Hash type_hash = new MD5_Hash();
                tbSignHashValue.Text = type_hash.GetHash(tbPathSignMessage.Text);
                try
                {
                    UnicodeEncoding ByteConverter = new UnicodeEncoding();

                    //Create byte arrays to hold original, encrypted, and decrypted data. 
                    byte[] dataToEncrypt = ByteConverter.GetBytes(tbSignHashValue.Text);
                    byte[] encryptedData;
                    using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                    {
                        encryptedData = clsRSA.RSAEncrypt(dataToEncrypt, tbPathSignKeypairs.Text, false);

                        //clsXML.SaveStringXMLToFile(publicAndPrivateKeys, Path_PrivateKey, saveFileDialog1, "Save Private Key in RSA");
                        //clsXML.SaveStringXMLToFile(justPublicKey, Path_PublicKey, saveFileDialog1, "Save Public Key in RSA");
                        //BinaryWriter bw = new BinaryWriter(File.Open(Path_DigitalSignature, FileMode.OpenOrCreate));
                        //bw.Write(encryptedData);
                        clsXML.SaveDigitalSignatureToFile(encryptedData, Path_DigitalSignature, saveFileDialog, "Save Digital Signature in RSA");
                    }
                }
                catch (ArgumentNullException)
                {
                    //Catch this exception in case the encryption did 
                    //not succeed.
                    MessageBox.Show("Encryption failed.");

                }
            }
            else
                MessageBox.Show(strCheckInput);
        }

        private void btBrownsVerifyMessage_Click(object sender, EventArgs e)
        {
            openFileDialog.Title = "Open file to verify";
            openFileDialog.Filter = "All files (*.*)|*.*";
            openFileDialog.FileName = "";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                tbPathVerifyMessage.Text = openFileDialog.InitialDirectory + openFileDialog.FileName;
            }
        }

        private void btBrownsVerifyKeypairs_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = "KeyPairs in RSA (*.rsakey)|*.rsakey";
            openFileDialog.Title = "Open KeyPairs in RSA";
            openFileDialog.FileName = "";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                tbPathVerifyKeypairs.Text = openFileDialog.InitialDirectory + openFileDialog.FileName;
            }
        }

        private void btBrownsVerifyDigitalSignature_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = "Digital signature in RSA(*.rsa)|*.rsa";
            openFileDialog.Title = "Open digital signature in RSA";
            openFileDialog.FileName = "";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                tbPathVerifyDigitalSignature.Text = openFileDialog.InitialDirectory + openFileDialog.FileName;
            }
        }

        private void btVerifyMessage_Click(object sender, EventArgs e)
        {
            string strCheckInput = clsChecker.CheckInPutVerifyAvailable(tbPathVerifyMessage, tbPathVerifyKeypairs, tbPathVerifyDigitalSignature);
            if (string.IsNullOrEmpty(strCheckInput))
            {
                // hash file 
                Type_Hash type_hash = new MD5_Hash();
                tbVerifyHashValue.Text = type_hash.GetHash(tbPathVerifyMessage.Text);
                try
                {
                    UnicodeEncoding ByteConverter = new UnicodeEncoding();
                    byte[] dataToEncrypt = ByteConverter.GetBytes(tbVerifyHashValue.Text);
                    byte[] encryptedData;
                    byte[] decryptedData;
                    using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                    {
                        encryptedData = File.ReadAllBytes(tbPathVerifyDigitalSignature.Text);

                        decryptedData = clsRSA.RSADecrypt(encryptedData, tbPathVerifyKeypairs.Text, false);
                        if (string.Compare(tbVerifyHashValue.Text, ByteConverter.GetString(decryptedData)) == 0)
                            MessageBox.Show("The message is integrited!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        else
                            MessageBox.Show("The message is not integrited!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (ArgumentNullException)
                {
                    MessageBox.Show("Encryption failed.");

                }
            }
            else
                MessageBox.Show(strCheckInput);
        }

        private void btnTimFileMH_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = null;
            openFileDialog.Title = "Open file to encrypt";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                tbDuongDanMH.Text = openFileDialog.InitialDirectory + openFileDialog.FileName;
                tbDuongDanTMMH.Text = Path.GetDirectoryName(tbDuongDanMH.Text);
            }
        }

        private void btnTimThuMucMH_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                tbDuongDanTMMH.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void btnMaHoaMH_Click(object sender, EventArgs e)
        {
            string KetQuaKiemTra = kiemTraThongTinHopLeMH();
            if (KetQuaKiemTra.Equals("true"))
            {
                DES_Algorithm des_algorithm = new DES_Algorithm(cbPaddingModeMH.Text, cbModeOfOperationMH.Text, tbMatKhauMH.Text, tbGiaTriIVMH.Text);
                bool result = des_algorithm.DES_Encrypt(tbDuongDanMH.Text, tbDuongDanTMMH.Text);
                if (result)
                    MessageBox.Show("Mã hoá thành công!", "Thuật toán DES");
                else
                    MessageBox.Show("Mã hoá thất bại!", "Thuật toán DES");
            }
            else
                MessageBox.Show(KetQuaKiemTra);
        }
        const int SIZE_PASS = 8;    // Mat Khau phai dai 7 ki tu (56 bits)
        const int SIZE_IV = 8;      // Gia Tri IV phai dai 8 ki tu (64 bits)
        private string kiemTraThongTinHopLeMH()
        {
            // kiem tra Mat Khau phai la 8 ki tu
            if (tbMatKhauMH.Text.Length == SIZE_PASS)
                // kiem tra Gia Tri IV phai la 8 ki tu
                if (tbGiaTriIVMH.Text.Length == SIZE_IV)
                    // kiem thong tin ve duong dan file
                    if (File.Exists(tbDuongDanMH.Text))
                    {
                        // kiem tra thong tin ve duong dan thu muc
                        if (Directory.Exists(tbDuongDanTMMH.Text))
                            return "true";
                        else
                            return "Đường dẫn thư mục không hợp lệ!.";
                    }
                    else
                        return "Đường dẫn file không hợp lệ!.";
                else
                    return "Giá trị IV phải dài SIZE_IV kí tự!.".Replace("SIZE_IV", SIZE_IV.ToString());
            else
                return "Mật khẩu phải dài SIZE_PASS kí tự!.".Replace("SIZE_PASS", SIZE_PASS.ToString());
        }

        private void btTimThuMucGM_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                tbDuongDanTMGM.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void btGiaiMaGM_Click(object sender, EventArgs e)
        {
            string KetQuaKiemTra = kiemTraThongTinHopLeGM();
            if (KetQuaKiemTra.Equals("true"))
            {
                DES_Algorithm des_algorithm = new DES_Algorithm(cbPaddingModeGM.Text, cbModeOfOperationGM.Text, tbMatKhauGM.Text, tbGiaTriIVGM.Text);
                bool result = des_algorithm.DES_Decrypt(tbDuongDanGM.Text, tbDuongDanTMGM.Text);
                if (result)
                    MessageBox.Show("Giải mã thành công!", "Thuật toán DES");
                else
                    MessageBox.Show("Giải mã thất bại!", "Thuật toán DES");
            }
            else
                MessageBox.Show(KetQuaKiemTra);
        }
        private string kiemTraThongTinHopLeGM()
        {
            // kiem tra Mat Khau phai la 8 ki tu
            if (tbMatKhauGM.Text.Length == SIZE_PASS)
                // kiem tra Gia Tri IV phai la 8 ki tu
                if (tbGiaTriIVGM.Text.Length == SIZE_IV)
                    // kiem thong tin ve duong dan file
                    if (File.Exists(tbDuongDanGM.Text))
                    {
                        // kiem tra thong tin ve duong dan thu muc
                        if (Directory.Exists(tbDuongDanTMGM.Text))
                            return "true";
                        else
                            return "Đường dẫn thư mục không hợp lệ!.";
                    }
                    else
                        return "Đường dẫn file không hợp lệ!.";
                else
                    return "Giá trị IV phải dài SIZE_IV kí tự!.".Replace("SIZE_IV", SIZE_IV.ToString());
            else
                return "Mật khẩu phải dài SIZE_PASS kí tự!.".Replace("SIZE_PASS", SIZE_PASS.ToString());
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // chon du lieu cho combobox trong Ma Hoa
            cbPaddingModeMH.SelectedIndex = 0;
            cbModeOfOperationMH.SelectedIndex = 0;
            // chon du lieu cho combobox trong Giai Ma
            cbPaddingModeGM.SelectedIndex = 0;
            cbModeOfOperationGM.SelectedIndex = 0;
        }

        private void btTimFileGM_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = "Encrypt File(.DES)|*.DES";
            openFileDialog.Title = "Open file to decrypt";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                tbDuongDanGM.Text = openFileDialog.InitialDirectory + openFileDialog.FileName;
                tbDuongDanTMGM.Text = Path.GetDirectoryName(tbDuongDanGM.Text);
            }
        }

        private void btExit_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
